package com.xbongbong.crm.perform.command.delete;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDeleteService;
import com.xbongbong.crm.service.permission.CustomerPermissionServiceImpl;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasProcessDataModel;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.dto.FormDataThoroughDeleteDTO;
import com.xbongbong.paas.pojo.vo.FormDataDeleteBatchVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.ConstantUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.pojo.delete.ErrorDataPojo;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.contact.pojo.dto.ContactDeleteBatchDTO;
import com.xbongbong.pro.contactuser.pojo.dto.ContactUserDeleteBatchDTO;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerCommunicateDeleteBatchDTO;
import com.xbongbong.pro.customeruser.pojo.dto.CustomerUserDeleteBatchDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.domain.entity.UpdateDataValueEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.invoice.pojo.dto.InvoiceDeleteBatchDTO;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.opportunity.pojo.dto.OpportunityDeleteBatchDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyDeletePermissionDTO;
import com.xbongbong.pro.pushnotify.dto.PushNotifyDeleteDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.workorder.pojo.dto.QuotationDeleteBatchDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CustomerFocusEntity;
import com.xbongbong.saas.domain.entity.PaymentBalanceEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.PaymentBalanceEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author 吴峰
 * @date 2022/02/08 14:44
 */
@Service("customerDeleteServiceImpl")
public class CustomerDeleteServiceImpl extends AbstractCrmDeleteService<PaasFormEntityExt, CustomerEntityExt> implements CustomerDeleteService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerDeleteServiceImpl.class);

    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private PaasProcessDataModel paasProcessDataModel;
    @Resource
    private UserModel userModel;
    @Resource
    private CustomerPermissionServiceImpl customerPermissionServiceImpl;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PushModel pushModel;
    @Resource
    private CustomerUserModel customerUserModel;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
    }

    @Override
    public FormDataDeleteBatchVO deleteWorkflow(FormDataDeleteBatchDTO formDataDeleteBatchDTO) throws XbbException {
        List<Long> contactIdIn = formDataDeleteBatchDTO.getDataIdList();
        String corpid = formDataDeleteBatchDTO.getCorpid();
        customerModel.deleteBatch(contactIdIn, corpid);
        customerUserModel.batchDeleteByCustomerId( corpid, contactIdIn, null);

        return new FormDataDeleteBatchVO();
    }

    @Override
    public void validatePermission(FormDataDeleteBatchDTO formDataDeleteBatchDTO) throws XbbException {
        if (formDataDeleteBatchDTO.getDataIdList().size() > 200) {
            // 客户删除，最多200条
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100079.getCode(), SystemErrorCodeEnum.API_ERROR_100079.getMsg(), 200);
        }
        VerifyDeletePermissionDTO verifyDeletePermissionDTO = new VerifyDeletePermissionDTO();
        BeanUtil.copyProperties(formDataDeleteBatchDTO, verifyDeletePermissionDTO);
        ProPermissionHelp.verifyDeletePermission(verifyDeletePermissionDTO);
    }

    @Override
    public FormDataDeleteBatchVO deleteBatchNoPermission(FormDataDeleteBatchDTO formDataDeleteBatchDTO, PaasFormEntityExt form) throws XbbException {
        List<CustomerEntityExt> list = deleteEsData(formDataDeleteBatchDTO, formDataDeleteBatchDTO.getDataIdList(), formDataDeleteBatchDTO.getCorpid());
        ErrorDataPojo errorDataPojo = notAllowData(formDataDeleteBatchDTO, list);

        List<Long> deleteIdIn = deleteData(formDataDeleteBatchDTO, errorDataPojo.getDeleteList(), list, formDataDeleteBatchDTO.getCorpid());
        log(formDataDeleteBatchDTO, list, errorDataPojo);
        return new FormDataDeleteBatchVO(errorDataPojo.getErrorDataList(), errorDataPojo.getErrorTypeList(), errorDataPojo.getErrorDataMemo(), deleteIdIn);
    }

    @Override
    public List<CustomerEntityExt> deleteEsData(FormDataDeleteBatchDTO formDataDeleteBatchDTO, List<Long> dataIdIn, String corpid) throws XbbException {
        // 过滤不允许删除的客户
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("ids", dataIdIn);
        param.put("del", DelEnum.NORMAL.getDel());
        List<CustomerEntityExt> customerList = customerModel.findEntitys(param);
        if (Objects.isNull(customerList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        //兼容删除脏数据
        if (!Objects.equals(dataIdIn.size(), customerList.size())) {
            customerList = paasEsModel.getByIdList(dataIdIn, corpid, null, IndexTypeEnum.IDX_SAAS_CUSTOMER, CustomerEntityExt.class);
        }
        return customerList;
    }

    @Override
    public ErrorDataPojo notAllowData(FormDataDeleteBatchDTO formDataDeleteBatchDTO,  List<CustomerEntityExt> list) throws XbbException {
        String corpid = formDataDeleteBatchDTO.getCorpid();
        // 获取有合同的客户
        List<Long> customerIdIn = new ArrayList<>();
        list.forEach(item->{
            customerIdIn.add(item.getId());
        });
        BoolQueryBuilder booleanQuery = boolQuery();
        String customerAttr = ContractEnum.LINK_CUSTOMER.getAttr();
        String customerContactAttr = ContactEnum.CUSTOMER_NAME.getAttr();
        String linkCustomer = StringConstant.JSON_DATA +StringConstant.POINT + customerAttr;
        booleanQuery.filter(termsQuery(linkCustomer, customerIdIn));
        booleanQuery.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        booleanQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        booleanQuery.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        List<String> fieldList = new ArrayList<>();
        fieldList.add(linkCustomer);
        List<PaasFormDataEntityExt> contractList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT, booleanQuery, PaasFormDataEntityExt.class, fieldList);
        if (Objects.isNull(contractList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        //客户对应的联系人进入审批
        Set<Long> hasContactCustomerID = new HashSet<>();
        if (commonHelp.isOpenWorkFlow(corpid)) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME), customerIdIn));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTACT.getType()));
            List<PaasFormDataEntityExt> contactFormDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT,
                    boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(ContactEnum.getAttrConnectData(ContactEnum.CUSTOMER_NAME), FieldTypeEnum.DATAID.getAlias()));
            contactFormDataList.forEach((item) -> {
                JSONObject data = item.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.get(customerContactAttr)) && data.getLong(customerContactAttr) > 0L) {
                    hasContactCustomerID.add(data.getLong(customerContactAttr));
                }
            });
        } else {
            List<PaasProcessDataEntity> approvalContactList = paasProcessDataModel.getInApprovalDataByIdCondition(XbbRefTypeEnum.CONTACT.getCode(), ContactEnum.CUSTOMER_NAME.getAttr(), customerIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
            approvalContactList.forEach((item) -> {
                JSONObject data = JSONObject.parseObject(item.getData());
                if (Objects.nonNull(data) && Objects.nonNull(data.get(customerContactAttr)) && data.getLong(customerContactAttr) > 0L) {
                    hasContactCustomerID.add(data.getLong(customerContactAttr));
                }
            });
        }
        Set<Long> hasContractCustomerId = new HashSet<>();
        contractList.forEach((item)->{
            JSONObject data = item.getData();
            if (Objects.nonNull(data) && Objects.nonNull(data.get(customerAttr)) && data.getLong(customerAttr) > 0L) {
                hasContractCustomerId.add(data.getLong(customerAttr));
            }
        });
        if (commonHelp.isOpenWorkFlow(corpid)) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.LINK_CUSTOMER), customerIdIn));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
            List<PaasFormDataEntityExt> contractFormDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT,
                    boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(ContractEnum.getAttrConnectData(ContractEnum.LINK_CUSTOMER), FieldTypeEnum.DATAID.getAlias()));
            contractFormDataList.forEach((item) -> {
                JSONObject data = item.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.get(customerAttr)) && data.getLong(customerAttr) > 0L) {
                    hasContractCustomerId.add(data.getLong(customerAttr));
                }
            });
        } else {
            List<PaasProcessDataEntity> approvalContractList = paasProcessDataModel.getInApprovalDataByIdCondition(XbbRefTypeEnum.CONTRACT.getCode(), ContractEnum.LINK_CUSTOMER.getAttr(), customerIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
            approvalContractList.forEach((item) -> {
                JSONObject data = JSONObject.parseObject(item.getData());
                if (Objects.nonNull(data) && Objects.nonNull(data.get(customerAttr)) && data.getLong(customerAttr) > 0L) {
                    hasContractCustomerId.add(data.getLong(customerAttr));
                }
            });
        }
        Set<String> errorTypeSet = new HashSet<>();
        List<Long> allowDeleteCustomerId = new ArrayList<>();
        List<String> errorDataList = new ArrayList<>();
        UserVO loginUser = formDataDeleteBatchDTO.getLoginUser();
        Boolean noPermission = !loginUser.isAdminOrBoss() && !loginUser.isMaxDataPermission();
        List<String> userIdIn = new ArrayList<>();
        if (noPermission) {
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(loginUser, userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), null);
            if (Objects.equals(dataPermission, DataPermissionEnum.SELF.getCode())) {
                //数据权限为本人时
                userIdIn = Collections.singletonList(loginUser.getUserId());
            } else {
                //数据权限不为本人时，需要判断下属员工是否是负责人
                userIdIn = userModel.getSubIdListByDataPermission(dataPermission, loginUser.getUserId(), loginUser.getCorpid(), BasicConstant.ONE, false);
            }
        }
        Set<Long> hasApprovalPaymentSheetCustomerId = new HashSet<>();
        if (commonHelp.isOpenWorkFlow(corpid)) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(PaymentSheetEnum.getEsAttr4Keyword(PaymentSheetEnum.CUSTOMER_ID), customerIdIn));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET.getType()));
            List<PaasFormDataEntityExt> formDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET,
                    boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(PaymentSheetEnum.getAttrConnectData(PaymentSheetEnum.CUSTOMER_ID), FieldTypeEnum.DATAID.getAlias()));
            formDataList.forEach(item -> {
                JSONObject data = item.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.get(PaymentSheetEnum.CUSTOMER_ID.getAttr())) && data.getLong(PaymentSheetEnum.CUSTOMER_ID.getAttr()) > 0L) {
                    hasApprovalPaymentSheetCustomerId.add(data.getLong(PaymentSheetEnum.CUSTOMER_ID.getAttr()));
                }
            });
        } else {
            List<PaasProcessDataEntity> approvalPaymentSheetList = paasProcessDataModel.getInApprovalDataByIdAndTypeCondition(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), PaymentSheetEnum.CUSTOMER_ID.getAttr(), customerIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
            approvalPaymentSheetList.forEach((item) -> {
                JSONObject data = JSONObject.parseObject(item.getData());
                if (Objects.nonNull(data) && Objects.nonNull(data.get(PaymentSheetEnum.CUSTOMER_ID.getAttr())) && data.getLong(PaymentSheetEnum.CUSTOMER_ID.getAttr()) > 0L) {
                    hasApprovalPaymentSheetCustomerId.add(data.getLong(PaymentSheetEnum.CUSTOMER_ID.getAttr()));
                }
            });
        }
        List<PaasFormDataEntityExt> paymentSheetList = paymentSheetModel.getPaymentSheetEsDataListByCustomerIds(corpid,customerIdIn,Arrays.asList(PaymentSheetTypeEnum.RED_PREPAYMENT.getCode(),PaymentSheetTypeEnum.PREPAYMENT.getCode()));
        Set<Long> hasPaymentSheetCustomerId = new HashSet<>();
        paymentSheetList.forEach((item)->{
            JSONObject data = item.getData();
            if (Objects.nonNull(data) && Objects.nonNull(data.get(PaymentSheetEnum.CUSTOMER_ID.getAttr())) && data.getLong(PaymentSheetEnum.CUSTOMER_ID.getAttr()) > 0L) {
                hasPaymentSheetCustomerId.add(data.getLong(PaymentSheetEnum.CUSTOMER_ID.getAttr()));
            }
        });
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            // 判断审批中
            CustomerEntityExt item = (CustomerEntityExt) iterator.next();
            Long customerId = item.getId();
            if (hasContractCustomerId.contains(customerId)) {
                // 含有合同的id
                iterator.remove();
                JSONObject data = item.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.get(CustomerManagementEnum.NAME.getAttr()))){
                    errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_CONTRACT_NOT_DEL));
                    errorDataList.add(data.getString(CustomerManagementEnum.NAME.getAttr()));
                }
                continue;
            }
            if (hasContactCustomerID.contains(customerId)) {
                // 有存在审批中联系人的id
                iterator.remove();
                JSONObject data = item.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.get(CustomerManagementEnum.NAME.getAttr()))){
                    errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_CONTACT_NOT_DEL));
                    errorDataList.add(data.getString(CustomerManagementEnum.NAME.getAttr()));
                }
                continue;
            }
            if(CollectionsUtil.isNotEmpty(hasApprovalPaymentSheetCustomerId)){
                if(hasApprovalPaymentSheetCustomerId.contains(customerId)){
                    iterator.remove();
                    JSONObject data = item.getData();
                    if (Objects.nonNull(data) && Objects.nonNull(data.get(CustomerManagementEnum.NAME.getAttr()))){
                        errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_P_M_B_NOT_DEL));
                        errorDataList.add(data.getString(CustomerManagementEnum.NAME.getAttr()));
                    }
                    continue;
                }
            }
            if(CollectionsUtil.isNotEmpty(hasPaymentSheetCustomerId)){
                if(hasPaymentSheetCustomerId.contains(customerId)){
                    iterator.remove();
                    JSONObject data = item.getData();
                    if (Objects.nonNull(data) && Objects.nonNull(data.get(CustomerManagementEnum.NAME.getAttr()))){
                        errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_PAYMENTSHEET_NOT_DEL));
                        errorDataList.add(data.getString(CustomerManagementEnum.NAME.getAttr()));
                    }
                    continue;
                }
            }
            item.setDataId(customerId);
            Integer isPublic = FastJsonHelper.getIntegerOrDefaultFromFormData(item.getData(), CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
            // 除公海客户且不是最大的数据权限，自己或其下属不是负责人则不能删除该客户
            if (noPermission && !Objects.equals(isPublic, 1) && !customerPermissionServiceImpl.checkDelPermission(userIdIn, item, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                iterator.remove();
                JSONObject data = item.getData();
                if (Objects.nonNull(data) && Objects.nonNull(data.get(CustomerManagementEnum.NAME.getAttr()))){
                    errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.NO_PERMISSION_CUSTOMER_DEL));
                    errorDataList.add(data.getString(CustomerManagementEnum.NAME.getAttr()));
                }
                continue;
            }
            allowDeleteCustomerId.add(customerId);
        }
        List<String> errorTypeList = new ArrayList<>(errorTypeSet);
        return new ErrorDataPojo(errorDataList, errorTypeList, ConstantUtil.getErrorDataMemo(errorTypeList, errorDataList), allowDeleteCustomerId);
    }

    @Override
    public List<Long> deleteData(FormDataDeleteBatchDTO customerDeleteBatchDTO, List<Long> allowDeleteCustomerId, List<CustomerEntityExt> list, String corpid) throws XbbException {
        List<Long> customerCommunicateIdIn = new ArrayList<>();
        List<Long> invoiceIdIn = new ArrayList<>();
        List<Long> opportunityIdIn = new ArrayList<>();
        List<Long> contactIdIn = new ArrayList<>();
        List<Long> quotationIdIn = new ArrayList<>();
        Set<Long> deletePayMentBalanceId = new HashSet<>();
        try {
            List<Long> isPublicCustomerIdIn = new ArrayList<>();
            if (!allowDeleteCustomerId.isEmpty()) {
                List<UpdateDataEntity> updateDataList = new ArrayList<>();
                allowDeleteCustomerId.forEach((item)->{
                    UpdateDataEntity updateDataEntity = new UpdateDataEntity();
                    List<UpdateDataValueEntity> updateDataValueList = new ArrayList<>();
                    UpdateDataValueEntity isPublic = new UpdateDataValueEntity();
                    isPublic.setValue(1);
                    isPublic.setKey(CustomerManagementEnum.IS_PUBLIC.getAttr());
                    isPublic.setEsKey(CustomerManagementEnum.IS_PUBLIC.getAttr());
                    isPublicCustomerIdIn.add(item);
                    updateDataValueList.add(isPublic);
                    updateDataEntity.setId(item);
                    updateDataEntity.setCorpid(corpid);
                    long now = DateUtil.getInt();
                    updateDataEntity.setUpdateTime(now);
                    updateDataEntity.setData(updateDataValueList);
                    updateDataList.add(updateDataEntity);
                });



                if(!updateDataList.isEmpty()) {
                    if(BasicConstant.ONE.equals(customerDeleteBatchDTO.getSingleFlag())
                            && BasicConstant.ONE.equals(updateDataList.size())){
                        customerModel.updateBatch(updateDataList,corpid, WriteRequest.RefreshPolicy.NONE);
                    }else {
                        customerModel.updateBatch(updateDataList, corpid);
                    }
                }
                if (CollectionsUtil.isNotEmpty(allowDeleteCustomerId) && Objects.isNull(customerDeleteBatchDTO.getIsRemoveCompletely())) {
                    customerModel.deleteBatch(allowDeleteCustomerId, corpid);
                    deleteStaticMarket(corpid, allowDeleteCustomerId, BasicConstant.ONE);
                } else if (CollectionsUtil.isNotEmpty(allowDeleteCustomerId) && Objects.equals(customerDeleteBatchDTO.getIsRemoveCompletely(), BasicConstant.ONE)) {
                    customerModel.thoroughDeleteBatch(allowDeleteCustomerId, corpid, DelEnum.REMOVE_COMPLETELY.getDel());
                    FormDataThoroughDeleteDTO formDataThoroughDeleteDTO = new FormDataThoroughDeleteDTO();
                    BeanUtil.copyProperties(customerDeleteBatchDTO, formDataThoroughDeleteDTO);
                    formDataThoroughDeleteDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                    deleteCustomerCommunicate(formDataThoroughDeleteDTO, allowDeleteCustomerId);
                    // 这个会在之后统一处理
                    // deleteStaticMarket(corpid, allowDeleteCustomerId, BasicConstant.ONE);
                }
                // 取消关注
                deleteCustomerFocus(customerDeleteBatchDTO, allowDeleteCustomerId);
                // 删除发票
                invoiceIdIn = deleteInvoice(customerDeleteBatchDTO, allowDeleteCustomerId);
                // 删除负责人
                CustomerUserDeleteBatchDTO customerUserDeleteBatchDTO = new CustomerUserDeleteBatchDTO();
                BeanUtil.copyProperties(customerDeleteBatchDTO, customerUserDeleteBatchDTO);
                customerUserDeleteBatchDTO.setCustomerIdIn(allowDeleteCustomerId);
                // todo
                // customerUserService.deleteBatch(customerUserDeleteBatchDTO);
                // 删除机会
                opportunityIdIn = deleteOpportunity(customerDeleteBatchDTO, allowDeleteCustomerId);
                // 删除联系人
                contactIdIn = deleteContact(customerDeleteBatchDTO, allowDeleteCustomerId);
                // 删除报价单
                quotationIdIn = deleteQuotation(customerDeleteBatchDTO, allowDeleteCustomerId);
                // 删除跟进记录 TODO 卡特说注释掉，在彻底删除时，删掉跟进记录
//                customerCommunicateIdIn = deleteCustomerCommunicate(customerDeleteBatchDTO, allowDeleteCustomerId);
                //预收款余额表对应的删除
                BoolQueryBuilder payMBQuery = boolQuery();
                payMBQuery.filter(termsQuery(PaymentBalanceEnum.CUSTOMER_ID.getAttr(), allowDeleteCustomerId));
                payMBQuery.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                payMBQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                List<PaymentBalanceEntity> payMentBalanceList = esHelper.findByScroll(IndexTypeEnum.IDX_PAYMENT_BALANCE, payMBQuery, PaymentBalanceEntity.class, Arrays.asList("id",PaymentBalanceEnum.CUSTOMER_ID.getAttr(),PaymentBalanceEnum.ADVANCE_PAYMENT_BALANCE.getAttr()));
                //预收款余额等于0,存id
                if(CollectionsUtil.isNotEmpty(payMentBalanceList)){
                    for (PaymentBalanceEntity paymentBalanceEntity : payMentBalanceList) {
                        deletePayMentBalanceId.add(paymentBalanceEntity.getId());
                    }
                }
                deletePayMentBalance(customerDeleteBatchDTO,new ArrayList<>(deletePayMentBalanceId));
                PushNotifyDeleteDTO pushNotifyDeleteDTO = new PushNotifyDeleteDTO();
                BeanUtil.copyProperties(customerDeleteBatchDTO, pushNotifyDeleteDTO);
                pushNotifyDeleteDTO.setNeedDelNotifyIdList(allowDeleteCustomerId);
                pushNotifyDeleteDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                // 删除提醒
                pushModel.deletePushNotify(allowDeleteCustomerId, corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            }
            return allowDeleteCustomerId;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.perform.operate.delete.CustomerDeleteServiceImpl.delete", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 处理编辑接口(市场活动统计中间表)
     * @param corpid
     * @param idIn
     */
    public void deleteStaticMarket(String corpid, List<Long> idIn, Integer del) {
        Runnable runnable = () -> {
            try {
                // TODO
//                marketActivityForStaticService.deleteBatchMarketActivity(idIn, XbbRefTypeEnum.CUSTOMER_MANAGEMENT ,corpid, del);
            } catch (Exception e) {

            }
        };
        threadPoolBeanConfig.staticsMarketData().execute(runnable);
    }

    @Override
    public void log(FormDataDeleteBatchDTO formDataDeleteBatchDTO, List<CustomerEntityExt> list, ErrorDataPojo errorDataPojo) throws XbbException {
        String corpid = formDataDeleteBatchDTO.getCorpid();
        List<String> name = new ArrayList<>();
        List<Long> allowDeleteCustomerId = errorDataPojo.getDeleteList();
        if (!list.isEmpty()) {
            for(CustomerEntityExt entityExt : list){
                JSONObject data = entityExt.getData();
                String sheetName = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
                name.add(sheetName);
            }
        }

        OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
        if (Objects.equals(1, formDataDeleteBatchDTO.getIsBusinessRule())) {
            operateTypeEnum = OperateTypeEnum.RULE_DELETE;
        }
        //生成删除日志(区分单个删除和批量删除)
        String userId = formDataDeleteBatchDTO.getUserId();
        String userName = formDataDeleteBatchDTO.getLoginUserName();
        String nameStr = StringUtils.join(name, "，");
        if(allowDeleteCustomerId.size() > 1){
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getName(), allowDeleteCustomerId.size());
            List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            InfoArrPojo infoArrPojo = new InfoArrPojo();
            infoArrPojo.setTitle(CustomerManagementEnum.NAME.getAttrName());
            infoArrPojo.setContent(nameStr);
            infoArrPojoList.add(infoArrPojo);
            mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER, operateTypeEnum,
                    "", "", memo, formDataDeleteBatchDTO.getHttpHeader());
        } else if (Objects.equals(allowDeleteCustomerId.size(), 1)){
            // 防止极端情况nameStr为空，主要来自合并客户
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getName(), nameStr);
            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER, operateTypeEnum,
                    allowDeleteCustomerId.get(0).toString(), nameStr, memo, formDataDeleteBatchDTO.getHttpHeader());
        }
    }

    @Override
    public void deleteAfter(List<Long> dataIdList, FormDataDeleteBatchDTO formDataDeleteBatchDTO, PaasFormEntityExt form) throws XbbException {
        lowCodeExecuteService(dataIdList, form.getSaasMark(), form.getBusinessType(), form.getId(), formDataDeleteBatchDTO.getCorpid());
        // 工作流，业务规则
        startWorkflow(formDataDeleteBatchDTO, form.getBusinessRules(), dataIdList);

    }

    @Override
    public void rollback(List list, String corpid) {

    }


    @Override
    public List<Long> deleteCustomerCommunicate(FormDataThoroughDeleteDTO formDataThoroughDeleteDTO, List<Long> allowDeleteCustomerId) throws XbbException {
        String corpid = formDataThoroughDeleteDTO.getCorpid();
        List<Long> customerCommunicateIdIn = new ArrayList<>();
        try {
            if (CollectionsUtil.isEmpty(allowDeleteCustomerId)) {
                return new ArrayList<>();
            }
            CustomerCommunicateDeleteBatchDTO customerCommunicateDeleteBatchDTO = new CustomerCommunicateDeleteBatchDTO();
            BeanUtil.copyProperties(formDataThoroughDeleteDTO, customerCommunicateDeleteBatchDTO, true);
            Runnable runnable = () -> {
                try {
                    List<Long> deleteIdIn = new ArrayList<>();
                    allowDeleteCustomerId.forEach(item->{
                        if (Objects.nonNull(item)) {
                            deleteIdIn.add(item);
                        }
                    });
                    BoolQueryBuilder boolQueryBuilder = boolQuery();
                    CustomerCommunicateEnum anEnum = CustomerCommunicateEnum.CUSTOMER_NAME;
                    if (Objects.equals(formDataThoroughDeleteDTO.getBusinessType(), XbbRefTypeEnum.CLUE.getCode())) {
                        anEnum = CustomerCommunicateEnum.COMMUNICATE_BUSINESS;
                        boolQueryBuilder.filter(termQuery(CustomerCommunicateEnum.getEsAttr4Keyword(CustomerCommunicateEnum.COMMUNICATE_BUSINESS_TYPE), XbbRefTypeEnum.CLUE.getCode()));
                    }
                    boolQueryBuilder.filter(termsQuery(CustomerCommunicateEnum.getEsAttr4Keyword(anEnum), deleteIdIn));
                    boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    List<String> fieldList = new ArrayList<>();
                    fieldList.add(StringConstant.DATA_ID);
                    List<PaasFormDataEntityExt> customerCommunicateList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
                    if (Objects.isNull(customerCommunicateList)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                    }
                    customerCommunicateList.forEach((item)->{
                        customerCommunicateIdIn.add(item.getDataId());
                    });
                    Integer allTotal = customerCommunicateList.size();
                    Integer pageSize = 100;
                    Integer index = allTotal/pageSize + 1;
                    Integer page = 0;
                    Integer toIndex = 100;
                    for (int j = 0; j < index; j++) {
                        if (toIndex > allTotal) {
                            toIndex = allTotal;
                        }
                        List<PaasFormDataEntityExt> resultList = customerCommunicateList.subList(page, toIndex);
                        if (CollectionsUtil.isNotEmpty(resultList)) {
                            List<Long> deleteList = new ArrayList<>();
                            resultList.forEach((item)->{
                                deleteList.add(item.getDataId());
                            });
                            customerCommunicateDeleteBatchDTO.setIdIn(deleteList);
                            // todo
//                            customerCommunicateService.deleteBatch(customerCommunicateDeleteBatchDTO);
                            page = page + pageSize;
                            toIndex = page + pageSize;
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("customerServiceImpl.deleteCustomerCommunicate 执行出错：", e);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);


        } catch (Exception e) {
            LOGGER.error("customerServiceImpl.deleteCustomerCommunicate 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return customerCommunicateIdIn;
    }


    /**
     * 取消关注
     * @author 吴峰
     * @date 2019/3/14 16:28
     * @param customerDeleteBatchDTO
     * @param customerIdIn
     * @return void
     * @throws XbbException 业务异常
     */
    private void deleteCustomerFocus(FormDataDeleteBatchDTO customerDeleteBatchDTO, List<Long> customerIdIn) throws XbbException {
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(customerDeleteBatchDTO, true);
            param.put("customerIdIn", customerIdIn);
            param.put("del", DelEnum.NORMAL.getDel());
            List<CustomerFocusEntity> customerFocusList = customerFocusModel.findEntitys(param);
            if (Objects.isNull(customerFocusList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            List<Long> idIn = new ArrayList<>();
            for (CustomerFocusEntity item : customerFocusList) {
                idIn.add(item.getId());
            }
            if (!idIn.isEmpty()) {
                customerFocusModel.unFocusBatch(customerIdIn, customerDeleteBatchDTO.getCorpid());
            }
        } catch (Exception e) {
            LOGGER.error("customerServiceImpl.deleteCustomerFocus 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 删除发票
     * @author 吴峰
     * @date 2019/3/14 16:44
     * @param customerDeleteBatchDTO 前端传参
     * @param allowDeleteCustomerId 需要删除的客户id
     * @return void
     * @throws XbbException 业务异常
     */
    private List<Long> deleteInvoice(FormDataDeleteBatchDTO customerDeleteBatchDTO, List<Long> allowDeleteCustomerId) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String corpid = customerDeleteBatchDTO.getCorpid();
        List<Long> invoiceIdIn = new ArrayList<>();
        try {
            boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA + StringConstant.POINT+ InvoiceEnum.CUSTOMER_NAME.getAttr(), allowDeleteCustomerId));
            boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            List<PaasFormDataEntityExt> invoiceList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_INVOICE, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(invoiceList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }

            invoiceList.forEach((item)->{
                invoiceIdIn.add(item.getDataId());
            });
            if (!invoiceIdIn.isEmpty()) {
                InvoiceDeleteBatchDTO invoiceDeleteBatchDTO = new InvoiceDeleteBatchDTO();
                BeanUtil.copyProperties(customerDeleteBatchDTO, invoiceDeleteBatchDTO, true);
                invoiceDeleteBatchDTO.setDataIdList(invoiceIdIn);
                // TODO
//                invoiceService.deleteBatch(invoiceDeleteBatchDTO, DelEnum.DELETE);
            }
        } catch (Exception e) {
            LOGGER.error("customerServiceImpl.deleteInvoice 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return invoiceIdIn;
    }

    /**
     * 删除联系人
     * @author 吴峰
     * @date 2019/3/14 16:44
     * @param customerDeleteBatchDTO 前端传参
     * @param allowDeleteCustomerId 需要删除的客户id
     * @return void
     * @throws XbbException 业务异常
     */
    private List<Long> deleteContact(FormDataDeleteBatchDTO customerDeleteBatchDTO, List<Long> allowDeleteCustomerId) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String corpid = customerDeleteBatchDTO.getCorpid();
        List<Long> contactIdIn = new ArrayList<>();
        try {
            boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA + StringConstant.POINT+ ContactEnum.CUSTOMER_NAME.getAttr(), allowDeleteCustomerId));
            boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            List<PaasFormDataEntityExt> contactList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(contactList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }

            contactList.forEach((item)->{
                contactIdIn.add(item.getDataId());
            });
            if (!contactIdIn.isEmpty()) {
                ContactDeleteBatchDTO contactDeleteBatchDTO = new ContactDeleteBatchDTO();
                BeanUtil.copyProperties(customerDeleteBatchDTO, contactDeleteBatchDTO, true);
                contactDeleteBatchDTO.setDataIdList(contactIdIn);
                // TODO
                // contactService.deleteBatch(contactDeleteBatchDTO);
                ContactUserDeleteBatchDTO contactUserDeleteBatchDTO = new ContactUserDeleteBatchDTO();
                BeanUtil.copyProperties(customerDeleteBatchDTO, contactUserDeleteBatchDTO, true);
                contactUserDeleteBatchDTO.setContactIdIn(contactIdIn);
                // TODO
//                contactUserService.deleteBatch(contactUserDeleteBatchDTO);
            }
        } catch (Exception e) {
            LOGGER.error("customerServiceImpl.deleteContact 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return contactIdIn;
    }

    /**
     * 删除报价单
     * @author long.rao
     * @date 2019-09-29 17:13
     * @param customerDeleteBatchDTO 前端传参
     * @param allowDeleteCustomerId 需要删除的客户id
     * @return void
     * @throws XbbException 业务异常
     */
    private List<Long> deleteQuotation(FormDataDeleteBatchDTO customerDeleteBatchDTO, List<Long> allowDeleteCustomerId) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String corpid = customerDeleteBatchDTO.getCorpid();
        List<Long> quotationIdIn = new ArrayList<>();
        try {
            boolQueryBuilder.filter(termsQuery(QuotationEnum.getEsAttr4Keyword(QuotationEnum.CUSTOMER_ID), allowDeleteCustomerId));
            boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            List<PaasFormDataEntityExt> quotationList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_QUOTATION, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(quotationList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }

            quotationList.forEach((item)->{
                quotationIdIn.add(item.getDataId());
            });
            if (!quotationIdIn.isEmpty()) {
                QuotationDeleteBatchDTO quotationDeleteBatchDTO = new QuotationDeleteBatchDTO();
                BeanUtil.copyProperties(customerDeleteBatchDTO, quotationDeleteBatchDTO, true);
                quotationDeleteBatchDTO.setDataIdList(quotationIdIn);
                // TODO
//                quotationService.deleteBatch(quotationDeleteBatchDTO);
            }
        } catch (Exception e) {
            LOGGER.error("customerServiceImpl.deleteQuotation 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return quotationIdIn;
    }

    /**
     * 删除机会
     * @author 吴峰
     * @date 2019/3/14 16:44
     * @param customerDeleteBatchDTO 前端传参
     * @param allowDeleteCustomerId 需要删除的客户id
     * @return void
     * @throws XbbException 业务异常
     */
    private List<Long> deleteOpportunity(FormDataDeleteBatchDTO customerDeleteBatchDTO, List<Long> allowDeleteCustomerId) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        String corpid = customerDeleteBatchDTO.getCorpid();
        List<Long> opportunityIdIn = new ArrayList<>();
        try {
            boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA + StringConstant.POINT+ SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), allowDeleteCustomerId));
            boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            List<PaasFormDataEntityExt> opportunityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OPPORTUNITY, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(opportunityList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }

            opportunityList.forEach((item)->{
                opportunityIdIn.add(item.getDataId());
            });
            if (!opportunityIdIn.isEmpty()) {
                OpportunityDeleteBatchDTO opportunityDeleteBatchDTO = new OpportunityDeleteBatchDTO();
                BeanUtil.copyProperties(customerDeleteBatchDTO, opportunityDeleteBatchDTO, true);
                opportunityDeleteBatchDTO.setDataIdList(opportunityIdIn);
                // todo
//                opportunityService.deleteBatch(opportunityDeleteBatchDTO);
            }
        } catch (Exception e) {
            LOGGER.error("customerServiceImpl.deleteOpportunity 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return opportunityIdIn;
    }

    /**
     * 删除预收款余额为0的记录
     * @param customerDeleteBatchDTO
     * @param deletePayMentBalanceId
     * @return
     * @throws XbbException
     */
    private List<Long> deletePayMentBalance(FormDataDeleteBatchDTO customerDeleteBatchDTO, List<Long> deletePayMentBalanceId) throws XbbException {
        if(CollectionsUtil.isEmpty(deletePayMentBalanceId)){
            return deletePayMentBalanceId;
        }
        try {
            // todo
//            paymentBalanceService.deleteBatch(deletePayMentBalanceId,customerDeleteBatchDTO.getCorpid());
        } catch (Exception e) {
            LOGGER.error("customerServiceImpl.deletePayMentBalance 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return deletePayMentBalanceId;
    }
}
